package com.rytx.web.controller.ysp;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.rytx.common.config.MyAliPayConfig;
import com.rytx.common.core.controller.BaseController;
import com.rytx.common.core.domain.AjaxResult;
import com.rytx.common.core.domain.model.ArtUser;
import com.rytx.common.utils.AilNotifyUtils;
import com.rytx.common.utils.alipay.RequestUtil;
import com.rytx.system.domain.ysp.ArtFundingDetails;
import com.rytx.system.domain.ysp.ArtOrder;
import com.rytx.system.service.IArtFundingDetailsService;
import com.rytx.system.service.IArtOrderService;
import com.rytx.system.service.IArtUserService;
import com.rytx.system.wxpay.MyWXPayConfig;
import com.rytx.system.wxpay.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/callback")
public class ArtCallbackController extends BaseController {
    @Resource
    MyWXPayConfig myWXPayConfig;
    @Autowired
    private MyAliPayConfig myAliPayConfig;
    @Autowired
    private IArtOrderService artOrderService;
    @Autowired
    private IArtUserService artUserService;
    @Autowired
    private IArtFundingDetailsService artFundingDetailsService;

    /**
     * 免押 支付宝回调
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/alipay/createOrder")
    public String notify(HttpServletRequest request, HttpServletResponse response) {
        // 读取支付宝POST过来反馈信息
        Map<String, String> requestParams = RequestUtil.getRequestParams(request);
        String notifyParamStr = JSONObject.toJSONString(requestParams);
        logger.info("创建订单异步通知参数：{}", notifyParamStr);
        // 验证反馈信息的正确性，防止数据在传输过程中被篡改
        //return "success";
        //1、验签 (注意：只有支付宝才需要验签，微信支付不需要验签)
        boolean verifyResult =  AilNotifyUtils.rsaCheckV1(request,myAliPayConfig,logger);
        logger.info("创建订单异步通知验签结果：{}", verifyResult);
        if (!verifyResult) return "";
        //2、通知参数解析
        //Map<String, String[]> notifyParams = request.getParameterMap();
        //String notifyParamStr = JSONObject.toJSONString(notifyParams);
        //3、执行业务逻辑
        ArtOrder artOrder = new ArtOrder();
        artOrder.setOrderNo(requestParams.get("out_order_no"));
        List<ArtOrder> artOrderList = artOrderService.selectArtOrderList(artOrder);
        if(artOrderList.isEmpty()){
            //订单不存在，不做处理
            logger.info("订单不存在，不做处理{}",requestParams.get("out_order_no"));
        }else if(artOrderList.size() > 1){
            //订单存在多个，不做处理
            logger.info("订单存在多个技术人员处理{}",requestParams.get("out_order_no"));
        }else{
            if(!"SUCCESS".equals(request.getParameter("status"))) {
                logger.error( "订单支付失败，订单号：{}，支付宝资金授权订单号：{}", requestParams.get("out_order_no"), requestParams.get("auth_no"));
                return "";
            }
            artOrder = artOrderList.get(0);//只存在一个订单
            artOrder.setAliOrder(requestParams.get("operation_id"));
            artOrder.setZmAuthOrderNo(requestParams.get("auth_no"));
            artOrder.setOrderStatus("1");
            artOrder.setOrderDate(requestParams.get("gmt_trans"));

            if(artOrder.getFreezeAmount().compareTo(new BigDecimal(requestParams.get("amount"))) == 0){
                artOrder.setOrderStatus("1");//1已支付
                logger.info("订单冻结成功，订单号：{}，支付宝资金授权订单号：{}", requestParams.get("out_order_no"), requestParams.get("auth_no"));
            }else{
                artOrder.setOrderStatus("998"); // 支付金额与订单不一致
                logger.error( "冻结金额与订单押金不一致，订单号：{}，支付宝资金授权订单号：{}", requestParams.get("out_order_no"), requestParams.get("auth_no"));
            }

            if(artOrderService.updateArtOrder(artOrder) <= 0){
                logger.info("订单状态更新失败{}",requestParams.get("out_order_no"));
            }
        }
        //4、返回通知结果
        return "success";
    }

    /**
     * 支付 支付宝回调
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/alipay/notifyBuyOrder")
    public String notifyBuyOrder(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 读取支付宝POST过来反馈信息
            Map<String, String> requestParams = RequestUtil.getRequestParams(request);
            String notifyParamStr = JSONObject.toJSONString(requestParams);
            logger.info("创建订单异步通知参数：{}", notifyParamStr);
            // 验证反馈信息的正确性，防止数据在传输过程中被篡改
            //1、验签 (注意：只有支付宝才需要验签，微信支付不需要验签)

            boolean verifyResult = AlipaySignature.rsaCheckV1(requestParams, myAliPayConfig.getAlipayPublicKey(), myAliPayConfig.getCharset(), myAliPayConfig.getSignType());
//            boolean verifyResult = AilNotifyUtils.rsaCheckV1(request, myAliPayConfig, logger);
            logger.info("创建订单异步通知验签结果：{}", verifyResult);
            if (!verifyResult) return "";
            //2、通知参数解析
            //Map<String, String[]> notifyParams = request.getParameterMap();
            //String notifyParamStr = JSONObject.toJSONString(notifyParams);
            //3、执行业务逻辑
            ArtOrder order = new ArtOrder();
            order.setAliTradeNo(requestParams.get("out_trade_no"));
            List<ArtOrder> artOrderList = artOrderService.selectArtOrderList(order);
            if (artOrderList.isEmpty()) {
                //订单不存在，不做处理
                logger.info("订单不存在，不做处理{}", requestParams.get("out_trade_no"));
            } else if (artOrderList.size() > 1) {
                //订单存在多个，不做处理
                logger.info("订单号{}存在多个订单，技术人员处理", requestParams.get("out_trade_no"));
            } else {
                if (!"TRADE_SUCCESS".equals(request.getParameter("trade_status"))) {
                    logger.error("订单支付失败，订单号：{}，支付宝交易号：{}", requestParams.get("out_trade_no"), requestParams.get("trade_no"));
                    return "";
                }
                ArtOrder artOrder = artOrderList.get(0);//只存在一个订单
                // 1 商家需要验证该通知数据中的 out_trade_no 是否为商家系统中创建的订单号。
                if("2".equals(artOrder.getOrderType())){
                    if(!artOrder.getOrderNo().equals(requestParams.get("out_trade_no"))){
                        logger.error("订单号不相等，订单号：{}，支付宝交易号：{}", requestParams.get("out_trade_no"), requestParams.get("trade_no"));
                        return "";
                    }
                }else if("1".equals(artOrder.getOrderType()) && "1".equals(order.getLeaseType())){
                    if(!artOrder.getAliTradeNo().equals(requestParams.get("out_trade_no"))){
                        logger.error("订单号不相等，订单号：{}，支付宝交易号：{}", requestParams.get("out_trade_no"), requestParams.get("trade_no"));
                        return "";
                    }
                }

                // 2 判断 total_amount 是否确实为该订单的实际金额（即商家订单创建时的金额）。
                if("2".equals(artOrder.getOrderType())){
                    if (artOrder.getOrderAmount().compareTo(new BigDecimal(requestParams.get("total_amount"))) == 0) {
                        logger.info("订单支付成功，订单号：{}，支付宝交易号：{}", requestParams.get("out_trade_no"), requestParams.get("trade_no"));
                    } else {
                        artOrder.setOrderStatus("998"); // 支付金额与订单不一致
                        logger.error("支付金额与订单不一致，订单号：{}，支付宝交易号：{}", requestParams.get("out_trade_no"), requestParams.get("trade_no"));
                    }
                }else if("1".equals(artOrder.getOrderType()) && "1".equals(order.getLeaseType())){
                    if (artOrder.getFreezeAmount().compareTo(new BigDecimal(requestParams.get("total_amount"))) == 0) {
                        logger.info("订单支付成功，订单号：{}，支付宝交易号：{}", requestParams.get("out_trade_no"), requestParams.get("trade_no"));
                    } else {
                        artOrder.setOrderStatus("998"); // 支付金额与订单不一致
                        logger.error("支付金额与订单不一致，订单号：{}，支付宝交易号：{}", requestParams.get("out_trade_no"), requestParams.get("trade_no"));
                    }
                }

                // 3 校验通知中的 seller_id（或者 seller_email ) 是否为 out_trade_no 这笔单据的对应的操作方（有的时候，一个商家可能有多个seller_id/seller_email）。
                // 就是商户号与seller_id是否对应。
                if(!myAliPayConfig.getSellerId().equals(requestParams.get("seller_id"))){
                    logger.error("商户号不相等，订单号：{}，支付宝交易号：{}", requestParams.get("out_trade_no"), requestParams.get("trade_no"));
                    return "";
                }

                // 4 验证 app_id 是否为该商家本身
                if(!myAliPayConfig.getAppId().equals(requestParams.get("app_id"))){
                    logger.error("app_id不相等，订单号：{}，支付宝交易号：{}", requestParams.get("out_trade_no"), requestParams.get("trade_no"));
                    return "";
                }

                order.setId(artOrder.getId());
                order.setOrderStatus("1");//1已支付

                if("1".equals(artOrder.getRecoveryStatus())){
                    order.setRecoveryStatus("2"); // 2 追缴成功
                    logger.info("订单追缴成功，订单号：{}，支付宝交易号：{}", requestParams.get("out_trade_no"), requestParams.get("trade_no"));
                    order.setOrderNo(artOrder.getOrderNo());
                    order.setUnfreezeAmount(artOrder.getOrderAmount()); // 追缴成功，解冻金额等于支付金额
                    order.setZmAuthOrderNo(artOrder.getZmAuthOrderNo()); // 免押授权资金号
                    order.setArtName(artOrder.getArtName());
                    // 解冻金额
                    boolean flag = artOrderService.zmnfreeze(order);
                    if(!flag){
                        logger.error("订单追缴成功，解冻金额失败，订单号：{}", requestParams.get("out_trade_no"));
                        // 把这几项设置为null，后面可以根据这些作为查询条件，通过定时任务跑批解冻
                        order.setUnfreezeAmount(null); // 追缴成功，解冻金额等于支付金额
                        order.setZmAuthOrderNo(null); // 免押授权资金号
                        order.setArtName(null);
                    }else {
                        logger.info("订单追缴成功，解冻金额成功，订单号：{}", requestParams.get("out_trade_no"));
                        // 解冻成功，如果是买断的，则把订单状态改为已完成，并且解冻剩余金额
                        if("2".equals(artOrder.getOrderType())){
                            AjaxResult ajaxResult = artOrderService.completeZmOrder(order);
                            if(ajaxResult.isSuccess()){
                                logger.info("订单追缴成功，买断订单解冻剩余金额成功，订单号：{}", requestParams.get("out_trade_no"));
                            }else {
                                logger.error("订单追缴成功，买断订单解冻剩余金额失败，订单号：{}", requestParams.get("out_trade_no"));
                                order.setUnfreezeAmount(null); // 追缴成功，解冻金额等于支付金额
                                order.setZmAuthOrderNo(null); // 免押授权资金号
                                order.setArtName(null);
                            }
                        }
                    }
                }

                if (artOrderService.updateArtOrder(order) <= 0) {
                    logger.info("订单状态更新失败，订单号：{}，支付宝交易号：{}", requestParams.get("out_trade_no"), requestParams.get("trade_no"));
                }else {
                    // 5 支付成功后，添加资金明细
                    ArtFundingDetails artFundingDetails = new ArtFundingDetails();
                    artFundingDetails.setOrderNo(artOrder.getOrderNo());
                    artFundingDetails.setFundingAmount(artOrder.getOrderAmount());
                    artFundingDetails.setFundingDate(new Date());
                    artFundingDetails.setFundingType("1");//1收入
                    artFundingDetails.setFundingRemark(artOrder.getArtName() + ":支付宝支付");
                    artFundingDetails.setArtRentalId(artOrder.getArtRentalId());
                    artFundingDetails.setUserId(artOrder.getUserId().toString());
                    artFundingDetails.setArtName(artOrder.getArtName());
                    artFundingDetailsService.insertArtFundingDetails(artFundingDetails);
                }
            }
            //4、返回通知结果
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    /**
     * 支付 微信回调
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/wx/notifyWxBuyOrder")
    public String notifyWxBuyOrder(HttpServletRequest request, HttpServletResponse response) {

        try {
            // 读取微信参数
            request.setCharacterEncoding("UTF-8");
            Reader reader = request.getReader();
            BufferedReader buffer = new BufferedReader(reader);
            String line = buffer.readLine();
            StringBuffer temp = new StringBuffer();
            while (line != null) {
                temp.append(line);
                line = buffer.readLine();
            }
            buffer.close();
            reader.close();
            String xml = temp.toString();
            if (WXPayUtil.isSignatureValid(xml, myWXPayConfig.getKey())) {
                Map<String, String> map = WXPayUtil.xmlToMap(xml);
                String resultCode = map.get("result_code");
                String returnCode = map.get("return_code");
                if ("SUCCESS".equals(resultCode) && "SUCCESS".equals(returnCode)) {
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/xml");
                    Writer writer = response.getWriter();
                    BufferedWriter bufferedWriter = new BufferedWriter(writer);
                    bufferedWriter.write("<xml><return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg></xml>");
                    bufferedWriter.close();
                    writer.close();
                    String out_trade_no = map.get("out_trade_no"); //out_trade_no商户系统内部订单号，可以是数字、大小写字母_-*的任意组合且在同一个商户号下唯一。
                    String transaction_id = map.get("transaction_id");  //transaction_id微信支付系统生成的订单号。
                    String openid = map.get("openid");
                    String attach = map.get("attach");

                   // ------------------------------
                    //3、执行业务逻辑
                    ArtOrder order = new ArtOrder();
                    order.setWechatOrder(out_trade_no);

                    List<ArtOrder> artOrderList = artOrderService.selectArtOrderList(order);
                    if (artOrderList.isEmpty()) {
                        //订单不存在，不做处理
                        logger.info("微信订单订单不存在，不做处理{}",out_trade_no);
                    } else if (artOrderList.size() > 1) {
                        //订单存在多个，不做处理
                        logger.info("微信订单号{}存在多个订单，技术人员处理", out_trade_no);
                    } else {
                        ArtOrder artOrder = artOrderList.get(0);//只存在一个订单
                        // 就是商户号与seller_id是否对应。
                        order.setId(artOrder.getId());
                        order.setOrderStatus("1");//1已支付
                        if (artOrderService.updateArtOrder(order) <= 0) {
                            logger.info("订单状态更新失败，微信订单号：{}，微信交易号：{}", out_trade_no, transaction_id);
                        }else {
                            logger.info("微信订单回调数据,OrderNo：{}，数据：{}", out_trade_no,JSONObject.toJSONString(map));
                            // 5 支付成功后，添加资金明细
                            ArtFundingDetails artFundingDetails = new ArtFundingDetails();
                            artFundingDetails.setOrderNo(artOrder.getOrderNo());
                            artFundingDetails.setFundingAmount(artOrder.getOrderAmount());
                            artFundingDetails.setFundingDate(new Date());
                            artFundingDetails.setFundingType("1");//1收入
                            artFundingDetails.setFundingRemark(artOrder.getArtName() + ":微信支付");
                            artFundingDetails.setArtRentalId(artOrder.getArtRentalId());
                            artFundingDetails.setUserId(artOrder.getUserId().toString());
                            artFundingDetails.setArtName(artOrder.getArtName());
                            artFundingDetailsService.insertArtFundingDetails(artFundingDetails);
                        }
                    }

                } else {
                    return "数字签名异常";
                }
            }

            //4、返回通知结果
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    /**
     * 支付 支付宝回调  购物车订单
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/alipay/notifyCartBuyUrl")
    public String notifyCartBuyUrl(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 读取支付宝POST过来反馈信息
            Map<String, String> requestParams = RequestUtil.getRequestParams(request);
            String notifyParamStr = JSONObject.toJSONString(requestParams);
            logger.info("创建订单异步通知参数：{}", notifyParamStr);
            // 验证反馈信息的正确性，防止数据在传输过程中被篡改
            //1、验签 (注意：只有支付宝才需要验签，微信支付不需要验签)

            boolean verifyResult = AlipaySignature.rsaCheckV1(requestParams, myAliPayConfig.getAlipayPublicKey(), myAliPayConfig.getCharset(), myAliPayConfig.getSignType());
//            boolean verifyResult = AilNotifyUtils.rsaCheckV1(request, myAliPayConfig, logger);
            logger.info("创建订单异步通知验签结果：{}", verifyResult);
            if (!verifyResult) return "";
            //2、通知参数解析
            //Map<String, String[]> notifyParams = request.getParameterMap();
            //String notifyParamStr = JSONObject.toJSONString(notifyParams);
            //3、执行业务逻辑
            ArtOrder sel = new ArtOrder();
            sel.setAliTradeNo(requestParams.get("out_trade_no"));
            List<ArtOrder> artOrderList = artOrderService.selectArtOrderList(sel);
            if (artOrderList.isEmpty()) {
                //订单不存在，不做处理
                logger.info("订单不存在，不做处理{}", requestParams.get("out_trade_no"));
            } else {
                if (!"TRADE_SUCCESS".equals(request.getParameter("trade_status"))) {
                    logger.error("订单支付失败，订单号：{}，支付宝交易号：{}", requestParams.get("out_trade_no"), requestParams.get("trade_no"));
                    return "";
                }
                // 3 校验通知中的 seller_id（或者 seller_email ) 是否为 out_trade_no 这笔单据的对应的操作方（有的时候，一个商家可能有多个seller_id/seller_email）。
                // 就是商户号与seller_id是否对应。
                if(!myAliPayConfig.getSellerId().equals(requestParams.get("seller_id"))){
                    logger.error("商户号不相等，订单号：{}，支付宝交易号：{}", requestParams.get("out_trade_no"), requestParams.get("trade_no"));
                    return "";
                }
                // 4 验证 app_id 是否为该商家本身
                if(!myAliPayConfig.getAppId().equals(requestParams.get("app_id"))){
                    logger.error("app_id不相等，订单号：{}，支付宝交易号：{}", requestParams.get("out_trade_no"), requestParams.get("trade_no"));
                    return "";
                }

                BigDecimal totalAmount = new BigDecimal(0);
                Long userId = artOrderList.get(0).getUserId();
                StringBuffer sb = new StringBuffer();
                String orderStatus ="1";
               for(int i =0;i<artOrderList.size();i++){
                    ArtOrder artOrder =   artOrderList.get(i);
                    // 1 商家需要验证该通知数据中的 out_trade_no 是否为商家系统中创建的订单号。
                    if(!artOrder.getAliTradeNo().equals(requestParams.get("out_trade_no"))){
                        logger.error("订单号不相等，订单号：{}，支付宝交易号：{}", requestParams.get("out_trade_no"), requestParams.get("trade_no"));
                        return "";
                    }
                    totalAmount = totalAmount.add(artOrder.getOrderAmount());
                   //artOrder.setOrderStatus("1");1已支付

                    orderStatus = "1";

                    if(i>0){
                        sb.append("-");
                    }
                    sb.append(artOrder.getArtName());

                }

                // 2 判断 total_amount 是否确实为该订单的实际金额（即商家订单创建时的金额）。
                if (totalAmount.compareTo(new BigDecimal(requestParams.get("total_amount"))) == 0) {
                    logger.info("订单支付成功，订单号：{}，支付宝交易号：{}", requestParams.get("out_trade_no"), requestParams.get("trade_no"));
                } else {
                    orderStatus = "998";
                    logger.error("支付金额与订单不一致，订单号：{}，支付宝交易号：{}", requestParams.get("out_trade_no"), requestParams.get("trade_no"));

                }
                for( ArtOrder artOrder : artOrderList){
                    artOrder.setOrderStatus(orderStatus);
                    int i = artOrderService.updateArtOrder(artOrder);
                    if (i <= 0) {
                        logger.info("订单状态更新失败{}", requestParams.get("out_order_no"));
                    }
                }

                // 5 支付成功后，添加资金明细
                ArtFundingDetails artFundingDetails = new ArtFundingDetails();

                artFundingDetails.setFundingAmount(totalAmount);
                artFundingDetails.setFundingDate(new Date());
                artFundingDetails.setFundingType("1");//1收入
                artFundingDetails.setFundingRemark( "木丁艺术品购物车订单:支付宝支付");

                artFundingDetails.setUserId(userId.toString());
                artFundingDetails.setArtName(sb.toString());
                artFundingDetails.setTradeNo(requestParams.get("out_trade_no"));
                artFundingDetailsService.insertArtFundingDetails(artFundingDetails);
            }
            //4、返回通知结果
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    /**
     * 支付 微信回调  购物车订单
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/wx/notifyWxCartBuyUrl")
    public String notifyWxCartBuyUrl(HttpServletRequest request, HttpServletResponse response) {
        String out_trade_no = "";
        String transaction_id = "";

        try {
            // 读取微信参数
            request.setCharacterEncoding("UTF-8");
            Reader reader = request.getReader();
            BufferedReader buffer = new BufferedReader(reader);
            String line = buffer.readLine();
            StringBuffer temp = new StringBuffer();
            while (line != null) {
                temp.append(line);
                line = buffer.readLine();
            }
            buffer.close();
            reader.close();
            String xml = temp.toString();
            if (WXPayUtil.isSignatureValid(xml, myWXPayConfig.getKey())) {
                Map<String, String> map = WXPayUtil.xmlToMap(xml);
                String resultCode = map.get("result_code");
                String returnCode = map.get("return_code");
                if ("SUCCESS".equals(resultCode) && "SUCCESS".equals(returnCode)) {
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/xml");
                    Writer writer = response.getWriter();
                    BufferedWriter bufferedWriter = new BufferedWriter(writer);
                    bufferedWriter.write("<xml><return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg></xml>");
                    bufferedWriter.close();
                    writer.close();
                     out_trade_no = map.get("out_trade_no"); //out_trade_no商户系统内部订单号，可以是数字、大小写字母_-*的任意组合且在同一个商户号下唯一。
                     transaction_id = map.get("transaction_id");  //transaction_id微信支付系统生成的订单号。
                    String openid = map.get("openid");
                    String attach = map.get("attach");

                    // ------------------------------
                    //3、执行业务逻辑
                    ArtOrder order = new ArtOrder();
                    order.setWechatOrder(out_trade_no);
                    List<ArtOrder> artOrderList = artOrderService.selectArtOrderList(order);
                    if (artOrderList.isEmpty()) {
                        //订单不存在，不做处理
                        logger.info("订单不存在，不做处理{}", out_trade_no);
                    } else {
                        BigDecimal totalAmount = new BigDecimal(0);
                        Long userId = artOrderList.get(0).getUserId();
                        StringBuffer sb = new StringBuffer();
                        String orderStatus ="1";
                        for(int i =0;i<artOrderList.size();i++){
                            ArtOrder artOrder =   artOrderList.get(i);
                            totalAmount = totalAmount.add(artOrder.getOrderAmount());
                            //artOrder.setOrderStatus("1");1已支付
                            orderStatus = "1";

                            if(i>0){
                                sb.append("-");
                            }
                            sb.append(artOrder.getArtName());

                        }

                        for( ArtOrder artOrder : artOrderList){
                            artOrder.setOrderStatus(orderStatus);
                            int i = artOrderService.updateArtOrder(artOrder);
                            if (i <= 0) {
                                logger.info("订单状态更新失败,OrderNo：{}", artOrder.getOrderNo());
                            }
                        }

                        logger.info("微信购物车订单回调数据,OrderNo：{}，数据：{}", out_trade_no,JSONObject.toJSONString(map));

                        // 5 支付成功后，添加资金明细
                        ArtFundingDetails artFundingDetails = new ArtFundingDetails();
                        artFundingDetails.setFundingAmount(totalAmount);
                        artFundingDetails.setFundingDate(new Date());
                        artFundingDetails.setFundingType("1");//1收入
                        artFundingDetails.setFundingRemark( "木丁艺术品购物车订单:微信支付");
                        artFundingDetails.setUserId(userId.toString());
                        artFundingDetails.setArtName(sb.toString());
                        artFundingDetails.setTradeNo(out_trade_no);
                        artFundingDetailsService.insertArtFundingDetails(artFundingDetails);
                    }

                } else {
                    logger.error("数字签名异常，订单号：{}，支付宝交易号：{}", out_trade_no, transaction_id);
                    return "数字签名异常";
                }
            }

            //4、返回通知结果
            return "success";

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}
